package com.doujiao.auth.service.impl;

import com.doujiao.auth.mapper.AdminMenuMapper;
import com.doujiao.auth.service.AdminMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doujiao.core.auth.entity.AdminMenu;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2025-05-24
 */
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AdminMenuServiceImpl extends ServiceImpl<AdminMenuMapper, AdminMenu> implements AdminMenuService {

    @Override
    public List<AdminMenu> getMenuTree() {
        List<AdminMenu> allMenus = baseMapper.selectList(null);
        Map<Long, List<AdminMenu>> menuMap = new HashMap<>();
        
        // 按父ID分组
        allMenus.forEach(menu -> {
            menuMap.computeIfAbsent(menu.getParentId(), k -> new ArrayList<>()).add(menu);
        });
        
        // 构建树形结构
        return buildTree(0L, menuMap);
    }

    private List<AdminMenu> buildTree(Long parentId, Map<Long, List<AdminMenu>> menuMap) {
        List<AdminMenu> tree = new ArrayList<>();
        List<AdminMenu> children = menuMap.get(parentId);
        
        if (children != null) {
            for (AdminMenu child : children) {
                child.setChildren(buildTree(child.getId(), menuMap));
                tree.add(child);
            }
        }
        
        return tree;
    }
}

